﻿using System;
using System.Collections;
using System.ComponentModel;
using System.Linq;
using System.Web;
using System.Runtime.Caching;
using BIStudio.Framework;

namespace BIStudio.Framework.Cache
{
    /// <summary>
    ///     本地缓存管理器
    /// </summary>
    [Description("Local")]
    public class LocalCacheProvider : ICache
    {
        private static MemoryCache HttpCache
        {
            get { return MemoryCache.Default; }
        }

        public void Add<T>(string hashKey, T value, int cacheMinutes)
        {
            if (cacheMinutes > 0)
            {
                HttpCache.Set(hashKey, value, DateTimeOffset.Now.AddMinutes(cacheMinutes));
            }
            else
            {

                HttpCache.Set(hashKey, value, DateTime.MaxValue);
            }
        }


        public T Get<T>(string hashKey)
        {
            if (!(HttpCache[hashKey] is T))
                return default(T);
            else
                return (T)HttpCache[hashKey];
        }

        public void Remove(string hashKey)
        {
            HttpCache.Remove(hashKey);
        }

        public void Clear(string prefix)
        {
            HttpCache.Cast<DictionaryEntry>()
                .Select(item => item.Key.ToString())
                .Where(item => item.StartsWith(prefix))
                .ForEach(item => HttpCache.Remove(item));
        }

        public bool Contains(string hashKey)
        {
            return HttpCache.Contains(hashKey);
        }
    }
}